// pages/orderList/index.js
import {
  ApiOrderList,
  ApiOrderPay,
  ApiCancelPay,
  ApiChangeOrderStatus,
  ApiCancelExtendOrder
} from '../api/index'
import {
  getConfig
} from '../../api/index'
const app = getApp()
let {
  baseUrl,
  commonUpdate,
  commonUpload
} = app.globalData
var timer = null;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    num: 30,
    complete: '',
    inProgress: '',
    total: '',
    baseUrl,
    commonUpload,
    status: "1",
    makeDifference: false,
    statusFormatter: [{
      label: '待支付',
      value: '1'
    }, {
      label: '待接单',
      value: '2'
    }, {
      label: '已接单',
      value: '3'
    }, {
      label: '已出发',
      value: '4'
    }, {
      label: '已上门',
      value: '5'
    }, {
      label: '已完成',
      value: '6'
    }, {
      label: '已取消',
      value: '7'
    }, {
      label: '退款中',
      value: '8'
    }],
    loading: false,
    dataList: [],
    active: '进行中',
    List: [],
    steps: [{
        text: '已接单',
      },
      {
        text: '已出发',
      },
      {
        text: '已上门',
      },
      {
        text: '已完成',
      },
    ],
    letterCommitment: '',
    showDialog: false,
    alreadyData: {},
    activeNames: ['1'],
    showText: false,
  },

  iconClick(e) {
    let val = e.currentTarget.dataset.v.id
    /*   this.setData({
        'e.currentTarget.dataset.v.showText': true
      }) */

    let val1 = this.data.dataList.findIndex(item => {
      if (item.id == val) {
        return item
      }
    })

    this.setData({
      ['dataList[' + val1 + '].showText']: true
    })
    setTimeout(() => {
      this.setData({
        ['dataList[' + val1 + '].showText']: false
      })
    }, 2000);
  },
  onSupplementary(e) {
    let val = e.currentTarget.dataset.v.id
    let val1 = this.data.dataList.findIndex(item => {
      if (item.id == val) {
        return item
      }
    })
    this.setData({
      ['dataList[' + val1 + '].activeNames']: e.detail
    })
  },



  onCloseMakeDifference() {
    this.setData({
      makeDifference: false
    })
  },
  //补差价
  makeDifferenceButton(e) {
    this.setData({
      makeDifference: false
    })
    let opr = e.currentTarget.dataset.value
    if (opr == '补差价') {
      wx.navigateTo({
        url: `/pagesDoctor/makeDifference/index?id=${this.data.makeDifferenceData.currentTarget.dataset.v.id}`,
      })
    } else {
      wx.navigateTo({
        url: `/pagesDoctor/completeOrder/index?id=${this.data.makeDifferenceData.currentTarget.dataset.v.id}`,
      })
    }
  },


  /**
   * 生命周期函数--监听页面加载
   */
  // 增补费用
  supplementalFee(e) {
    wx.navigateTo({
      url: `/pagesDoctor/supplementalFee/index?id=${e.currentTarget.dataset.v.id}`,
    })
  },

  applyExtension(e) {
    wx.navigateTo({
      url: `/pagesDoctor/applyExtension/index?data=${JSON.stringify(e.currentTarget.dataset.v)}`,
    })
  },
  onLoad(options) {
    console.log(options.data)
    if (options.data && options.data.length > 0) {
      this.getOrderList(options.data)
      this.setData({
        active: options.data
      })
    }
    //获取协议
    getConfig().then(res => {
      res.data.forEach(item => {
        if (item.key == "letterCommitment") {
          this.setData({
            'letterCommitment': item.value
          })
        }
      })
    })
    /*    this.getOrderList('全部') */
  },


  //拿到订单列表数据
  getOrderList(val) {
    wx.showLoading({
      title: '加载中',
    })
    ApiOrderList({
      status: val
    }).then(res => {
      if (res.code == 200) {
        /*   this.data.List = [] */
        res.data.forEach(item => {
          if (item.extend_order.length > 0) {
            item.extend_order.forEach(i => {
              i.picArr = i.pic.split(',')
            })
          }
          item.showText = false
          item.activeNames = []
          //添加字段
          this.checkStatus(item)

        })



        this.setData({
          dataList: res.data,
          total: res.total,
          inProgress: res.inProgress,
          complete: res.complete
        })
      }
    }).finally(_ => {
      wx.hideLoading()
      wx.stopPullDownRefresh()
    })
  },
  //改变状态
  checkStatus(item) {
    this.data.statusFormatter.forEach(statusItem => {
      if (item.status == statusItem.value) {
        item.statusLabel = statusItem.label
      }
    })
  },

  forMateTime(start, end) {
    // 获取当前时间
    const currentTime = new Date();
    // 设置目标时间为今天的 19:59
    const targetTime = new Date();
    targetTime.setHours(start, end, 0, 0);
    // 计算前两个小时的时间
    const twoHoursBefore = new Date(targetTime.getTime() - 2 * 60 * 60 * 1000);
    // 判断当前时间是否在目标时间的前两个小时内
    if (currentTime >= twoHoursBefore && currentTime <= targetTime) {
      return true
    } else {
      return false
    }
  },

  //已经出门
  alreadyOut(val) {

    if (val.currentTarget.dataset.v.statusLabel == '已出发') {
      this.submitData(val)
    } else {
      this.setData({
        showDialog: true,
        alreadyData: val,
        num: 30
      })
      clearInterval(timer)
      timer = setInterval(() => {
        this.setData({
          num: this.data.num - 1
        })
        if (this.data.num == 0) {
          clearInterval(timer)
          this.confirmClose()
        }
      }, 1000);

    }

  },
  stopTz() {},
  confirmButton(res) {
    clearInterval(timer)
    console.log(res)
    if (res.type == 'confirm') {
      console.log('22')
      this.setData({
        showDialog: false
      })
      this.submitData(this.data.alreadyData)
    } else {
      this.confirmClose()
    }

  },
  confirmClose(res) {
    this.setData({
      showDialog: false
    })
  },
  submitData(val) {
    /*  order_time */
    let that = this
    let timeStart = val.currentTarget.dataset.v.order_time.split(' ')[1].slice(0, 5).split(':')
    let isTime = this.forMateTime(timeStart[0], timeStart[1])
    if (isTime || val.currentTarget.dataset.v.statusLabel == '已出发') {
      this.formateS(val)
    } else {
      wx.showModal({
        title: "当前时间超过就诊人预约时间两个小时，是否提前出发？",
        success(res) {
          if (res.confirm) {
            that.formateS(val)
          }
        }
      })
    }
  },

  //已出发状态修改
  formateS(val) {
    this.setData({
      loading: true
    })
    let that = this
    let value = val.currentTarget.dataset.v
    wx.showModal({
      title: "是否确认变更状态？",
      success(res) {
        if (res.confirm) {
          ApiChangeOrderStatus({
            order_id: value.id,
            status: Number(value.status) + 1
          }).then(res => {
            if (res.code == '200') {
              wx.showToast({
                title: "改变状态成功",
              })
              that.getOrderList('进行中')
              that.setData({
                active: '进行中'
              })
            }

          }).finally(_ => {
            that.setData({
              loading: false
            })
          })
        } else {
          that.setData({
            loading: false
          })
        }

      }
    })
  },


  alreadyOutCancel(val) {
    let value = val.currentTarget.dataset.v
    wx.navigateTo({
      url: `/pagesDoctor/cancelDoor/index?order_id=${value.id}`,
    })
  },

  //取消订单
  cancelExtendOrder(val) {
    console.log(val)
    let value = val.currentTarget.dataset.v[0]
    let that = this
    wx.showModal({
      title: "是否确认取消该数据？",
      success(res) {
        if (res.confirm) {
          ApiCancelExtendOrder(value.id).then(res => {
            if (res.code == '200') {
              wx.showToast({
                title: "取消成功",
              })
              that.getOrderList(that.data.active)
            }
          })
        }
      }

    })

  },

  // 过滤
  filterValue(val, item) {
    if (val == '全部') {
      this.data.List.push(item)
    } else {
      if (item.statusLabel == val) {
        this.data.List.push(item)
      }
    }

  },
  //切换页面
  onChangeTab(e) {
    console.log(e)
    this.setData({
      active: e.detail.name
    })
    this.getOrderList(e.detail.name)
  },
  //跳转到订单详情
  bindClickDetail(e) {
    console.log(e)
    wx.navigateTo({
      url: `/pages/orderListDetail/index?data=${JSON.stringify(e.currentTarget.dataset.v)}`,
    })
  },
  //继续付款
  continuePay(e) {
    ApiOrderPay(e.currentTarget.dataset.v.id).then(res => {
      if (res.code == '200') {
        let that = this
        wx.requestPayment({
          ...res.data,
          success(res) {
            /*      app.clearStatistics() */
            wx.showModal({
              title: '支付成功',
              showCancel: false,
              success(res) {
                this.setData({
                  active: '全部'
                })
                that.getOrderList('全部')
                /*   if (that.data.luckyDrawTime) {
                    wx.redirectTo({
                      url: '/pages/activity/index?router=/activity/paymentDraw',
                    })
                    
                  } else {
                    pathBack("pages/user/payOrInvoice/pay/index", 1)
                  } */
              }
            })
          },
          fail(res) {
            console.log('1111', res)
            wx.showModal({
              title: '支付失败',
              showCancel: false
            })
          }


        })
      }
    })
  },
  //取消订单
  cancelPay(e) {
    let that = this
    wx.showModal({
      title: "是否确认取消进行更改？",
      success() {
        ApiCancelPay(e.currentTarget.dataset.v.id).then(res => {
          if (res.code == '200') {
            wx.showToast({
              title: "取消成功",
            })
            that.setData({
              active: '已取消'
            })
            that.getOrderList('已取消')
          }
        })

      },
      fail(err) {
        console.log(err)
      }
    })


  },
  //立即评价
  evaluation(e) {
    wx.navigateTo({
      url: `/pagesDoctor/evaluation/index?id=${JSON.stringify(e.currentTarget.dataset.v)}`,
    })
  },
  //查看评价
  SearchEvaluation(e) {
    wx.navigateTo({
      url: `/pagesDoctor/searchEvaluation/index?id=${e.currentTarget.dataset.v.id}`,
    })
  },


  //订单反馈
  feedback(e) {
    wx.navigateTo({
      url: `/pagesDoctor/feedback/index?id=${e.currentTarget.dataset.v.id}`,
    })
  },

  //完成订单
  /*   completeOrder(e) {
      wx.navigateTo({
        url: `/pagesDoctor/completeOrder/index?id=${e.currentTarget.dataset.v.id}`,
      })
    }, */

  completeOrder(e) {
    if (e.currentTarget.dataset.v.extend_order.length > 0) {
      if (e.currentTarget.dataset.v.extend_order[0].status == '待支付') {
        wx.showModal({
          title: "当前增补费用还未支付，是否确认结束该订单？",
          success(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: `/pagesDoctor/completeOrder/index?id=${e.currentTarget.dataset.v.id}`,
              })
            }
          }
        })
      } else {
        wx.navigateTo({
          url: `/pagesDoctor/completeOrder/index?id=${e.currentTarget.dataset.v.id}`,
        })
      }
    } else {
      this.setData({
        makeDifference: true,
        makeDifferenceData: e
      })
    }



    //完成订单的提示
    /*   wx.navigateTo({
        url: `/pagesDoctor/completeOrder/index?id=${e.currentTarget.dataset.v.id}`,
      }) */
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getOrderList(this.data.active)
    if (typeof this.getTabBar === "function" &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.getOrderList(this.data.active)

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})